const axios = require("axios")
const { header_t, header_user_agent, time_second, tiems_count, cost_time, cycle_count } = require("./config")

//生成从minNum到maxNum的随机数
function RandomNumBoth(Min, Max) {
  var Range = Max - Min
  var Rand = Math.random()
  var num = Min + Math.round(Rand * Range) //四舍五入
  return num
}

//  完成游戏接口 需要参数状态以及耗时（单位秒）
let finish_api = "https://cat-match.easygame2021.com/sheep/v1/game/game_over?rank_score=1&rank_state=1&rank_time=%t&rank_role=1&skin=1"

let request = axios.create({
  headers: {
    t: header_t,
    "User-Agent": header_user_agent,
    Host: "cat-match.easygame2021.com",
    Connection: "keep-alive",
    charset: "utf-8",
    "Accept-Encoding": "gzip,compress,br,deflate",
    "content-type": "application/json",
    Referer: "https://servicewechat.com/wx141bfb9b73c970a9/17/page-frame.html",
  },
})
let tiems,
  true_count = 0,
  false_count = 0
function loop() {
  console.log("--开始羊了个羊通关--")
  let r_cost_time = cost_time === -1 ? RandomNumBoth(600, 3600) : cost_time
  console.log("设置通关时长为：" + r_cost_time + "s")
  let url = finish_api.replace("%t", r_cost_time)
  request
    .get(url)
    .then((res) => {
      if (res.data.err_code === 0) {
        true_count++
        console.log("通关成功--（完成数：" + cycle_count + " / " + true_count + "）")
      } else {
        console.log("then--通关失败-------")
        false_count++
      }
    })
    .catch((err) => {
      console.log("通关失败--" + err.message)
      false_count++
    })
    .finally((_) => {
      console.log("成功次数：" + true_count)
      console.log("失败次数：" + false_count)
    })
}

function start() {
  let a = time_second * 1000
  for (let i = 0; i < tiems_count; i++) {
    setTimeout(() => {
      tiems && loop()
    }, (a / tiems_count) * i)
  }
  tiems = setInterval(() => {
    if (true_count >= cycle_count) {
      console.log("---------- 关闭 ----------")
      clearInterval(tiems)
      tiems = undefined
      return
    }
    for (let i = 0; i < tiems_count; i++) {
      setTimeout(() => {
        tiems && loop()
      }, (a / tiems_count) * i)
    }
  }, a)
}

start()
